package cn.kuang.service;

import cn.kuang.mapper.MsgMapper;
import cn.kuang.mapper.UserMapper;
import cn.kuang.mapper.UserMsgMapper;
import cn.kuang.pojo.Msg;
import cn.kuang.pojo.User;
import cn.kuang.pojo.UserMsg;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 徽州大都督
 * @date 2020/7/23
 */
@Service
@Transactional
public class UserMsgService {

    @Autowired
    private UserMsgMapper userMsgMapper;

    @Autowired
    private MsgMapper msgMapper;

    @Autowired
    private UserMapper userMapper;

    public void addMsg(String content, String username) {

        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username",username);
        User user = userMapper.selectOne (wrapper);

        Msg msg = new Msg ();
        String mid = UUID.randomUUID ().toString ();
        msg.setMsgId (mid);
        msg.setMsgContent (content);
        msg.setMsgTime (new Date ());
        msgMapper.insert (msg);

        UserMsg userMsg = new UserMsg ();
        userMsg.setUid (user.getUid ());
        userMsg.setMsgId (mid);
        userMsgMapper.insert (userMsg);


    }

    public List<Msg> findByPage(Integer pages, Integer size) {

        Page<Msg> page = new Page<> (pages,size);
        /* this..selectPage (page,null);*/


        QueryWrapper<Msg> wrapper2 = new QueryWrapper<> ();
        wrapper2.orderByDesc ("msg_time"); //按时间进行降序

        this.msgMapper.selectPage (page,wrapper2);
        List<Msg> msgList = page.getRecords ();
        long total = page.getTotal ();


            msgList.forEach (msg -> {
                QueryWrapper<UserMsg> wrapper = new QueryWrapper<> ();
                wrapper.eq ("msg_id",msg.getMsgId ());
                UserMsg userMsg = userMsgMapper.selectOne (wrapper);
                msg.setTotal (total);
                QueryWrapper<User> wrapper1 = new QueryWrapper<> ();

                wrapper1.eq ("uid",userMsg.getUid ());
                User user = userMapper.selectOne (wrapper1);
                msg.setUser (user);
            });




        return msgList;

    }
}
